package cn.buddha.jec.util;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.EasyExcelFactory;
import com.alibaba.excel.ExcelReader;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.read.metadata.ReadSheet;
import com.alibaba.excel.write.metadata.WriteSheet;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;

/**
 * @ClassName TongExcelUtils
 * @Author 友野浩二
 * @Date 2020/4/7 19:06
 * @Description Excel工具类
 * @Version 1.0
 */
@Slf4j
public class TongExcelUtils {

    /**
     * @Author 友野浩二
     * @Description // 模型 解析监听器
     * @Date 2020/4/7 19:16
     * <pre>
     *     ModelExcelListener不能被spring管理，要每次读取excel都要new
     * </pre>
     */
    @Getter
    @Setter
    private static class ModelExcelListener extends AnalysisEventListener {
        private List<Object> excelDataList = new ArrayList<>();

        // 这个每一条数据解析都会来调用
        @Override
        public void invoke(Object o, AnalysisContext analysisContext) {
            // 将解析的每一行数据存储到 excelDatas 集合中
//            log.info("excel data is: {}", JSON.toJSONString(o));
            excelDataList.add(o);
        }

        @Override
        public void doAfterAllAnalysed(AnalysisContext analysisContext) {
            // 解析结束后销毁资源
            // 注意不要调用 excelDataList.clear(),否则 getExcelDataList() 为null
        }
    }

    /**
     * @return java.util.List<java.lang.Object>
     * @Author 友野浩二
     * @Description // 读取Excel(只读取sheet1)
     * @Date 2020/4/7 19:40
     * @Param [pathName(Excel文件路径), clazz(Excel对应的模型类)]
     */
    public static List<Object> readExcel(String pathName, Class clazz) {
        ModelExcelListener modelExcelListener = new ModelExcelListener();

//        ExcelReader excelReader = EasyExcel.read(pathName, clazz, modelExcelListener).build();
        ExcelReader excelReader = EasyExcelFactory.read(pathName, clazz, modelExcelListener).headRowNumber(0).build();
        ReadSheet readSheet = EasyExcel.readSheet(0).build();
        excelReader.read(readSheet);

        List<Object> excelDataList = modelExcelListener.getExcelDataList();

        excelReader.finish();// 这里千万别忘记关闭，读的时候会创建临时文件，到时磁盘会崩的

        return excelDataList;
    }

    /**
     * @return void
     * @Author 友野浩二
     * @Description // 写excel
     * @Date 2020/4/7 23:13
     * @Param [data(数据内容), pathName(Excel文件路径), sheetName, clazz(Excel对应的模型类)]
     */
    public static void writeExcel(List<Object> data, String pathName, String sheetName, Class clazz) {
        ExcelWriter excelWriter = EasyExcelFactory.write(pathName, clazz).build();
        WriteSheet writeSheet = EasyExcelFactory.writerSheet(sheetName).build();
        excelWriter.write(data, writeSheet);
        excelWriter.finish();//  千万别忘记finish 会帮忙关闭流
    }

}
